from typing import List, Optional
from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel

from app.services.ai_rule_service import AIRuleService, SmartLearningService

router = APIRouter(tags=["ai-rules"])
ai_rule_service = AIRuleService()
learning_service = SmartLearningService()

class RuleBuildRequest(BaseModel):
    building_type: str
    context: Optional[dict] = None

class FeedbackRequest(BaseModel):
    rule_id: str
    feedback_type: str  # "useful", "false_positive", "missed_issue"
    user_context: Optional[dict] = None

class PersonalizedRulesRequest(BaseModel):
    rule_set_id: str
    user_expertise: str = "intermediate"  # "beginner", "intermediate", "expert"

class RuleResponse(BaseModel):
    rule_set_id: str
    building_type: str
    total_rules: int
    created_at: str
    rules: List[dict]
    metadata: dict

@router.post("/ai-rules/build", response_model=RuleResponse)
async def build_ai_rules(request: RuleBuildRequest):
    """构建AI规则库"""
    try:
        rule_set = await ai_rule_service.build_ai_rules(
            request.building_type, 
            request.context
        )
        return rule_set
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"构建规则失败: {str(e)}")

@router.get("/ai-rules/history", response_model=List[RuleResponse])
async def get_rules_history(limit: int = Query(10, ge=1, le=50)):
    """获取AI规则构建历史"""
    try:
        history = await ai_rule_service.get_rules_history(limit)
        return history
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取历史记录失败: {str(e)}")

@router.get("/ai-rules/{rule_set_id}", response_model=RuleResponse)
async def get_rule_set(rule_set_id: str):
    """获取特定规则集详情"""
    try:
        rule_set = await ai_rule_service.get_rule_set(rule_set_id)
        return rule_set
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取规则集失败: {str(e)}")

@router.get("/ai-rules/templates/{building_type}")
async def get_rule_templates(building_type: str):
    """获取建筑类型规则模板"""
    try:
        templates = await ai_rule_service.get_base_rules(building_type)
        return {
            "building_type": building_type,
            "templates": templates,
            "total_templates": len(templates)
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取模板失败: {str(e)}")

@router.get("/ai-rules/categories")
async def get_rule_categories():
    """获取规则分类"""
    return {
        "categories": [
            {
                "name": "消防安全",
                "description": "消防通道、防火分区、疏散设施等",
                "severity_levels": ["严重", "中等", "轻微"]
            },
            {
                "name": "功能空间",
                "description": "房间尺寸、空间布局、使用功能等",
                "severity_levels": ["严重", "中等", "轻微"]
            },
            {
                "name": "安全防护",
                "description": "栏杆高度、防护措施、安全距离等",
                "severity_levels": ["严重", "中等"]
            },
            {
                "name": "节能标准",
                "description": "保温性能、采光通风、节能措施等",
                "severity_levels": ["中等", "轻微"]
            },
            {
                "name": "无障碍设计",
                "description": "坡道坡度、无障碍设施、通行宽度等",
                "severity_levels": ["中等", "轻微"]
            }
        ]
    }

@router.post("/ai-rules/feedback")
async def record_rule_feedback(request: FeedbackRequest):
    """记录规则反馈"""
    try:
        await learning_service.record_feedback(
            request.rule_id, 
            request.feedback_type, 
            request.user_context
        )
        return {"message": "反馈记录成功", "rule_id": request.rule_id}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"记录反馈失败: {str(e)}")

@router.post("/ai-rules/personalized")
async def get_personalized_rules(request: PersonalizedRulesRequest):
    """获取个性化规则集"""
    try:
        # 获取基础规则集
        rule_set = await ai_rule_service.get_rule_set(request.rule_set_id)
        
        # 应用个性化
        personalized_rules = await learning_service.get_personalized_rules(
            rule_set["rules"], 
            request.user_expertise
        )
        
        return {
            "rule_set_id": request.rule_set_id,
            "user_expertise": request.user_expertise,
            "total_rules": len(personalized_rules),
            "rules": personalized_rules,
            "personalization_notes": f"已为{request.user_expertise}用户优化规则"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"个性化规则失败: {str(e)}")

@router.get("/ai-rules/insights")
async def get_learning_insights():
    """获取学习洞察报告"""
    try:
        insights = await learning_service.get_learning_insights()
        return insights
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取洞察失败: {str(e)}")

@router.get("/ai-rules/demo")
async def get_demo_rules():
    """获取演示规则集"""
    return {
        "rule_set_id": "demo-001",
        "building_type": "commercial",
        "total_rules": 5,
        "created_at": "2024-12-19T10:30:00",
        "rules": [
            {
                "rule_id": "fire_door_width_demo",
                "category": "消防安全",
                "title": "防火门净宽度检查",
                "description": "疏散门净宽度不应小于1.4米",
                "condition": "element.Type == 'IfcDoor' AND element.IsFireExit == True",
                "threshold": 1.4,
                "unit": "m",
                "severity": "严重",
                "standard": "GB 50016-2014 建筑设计防火规范",
                "suggested_fix": "扩大门洞宽度或更换更大尺寸防火门"
            },
            {
                "rule_id": "office_height_demo",
                "category": "功能空间",
                "title": "办公室净高检查",
                "description": "办公室净高不应低于2.6米",
                "condition": "element.Type == 'IfcSpace' AND element.RoomType == 'Office'",
                "threshold": 2.6,
                "unit": "m",
                "severity": "中等",
                "standard": "JGJ 67-2006 办公建筑设计规范",
                "suggested_fix": "提高楼层高度或减少吊顶厚度"
            },
            {
                "rule_id": "corridor_width_demo",
                "category": "消防安全",
                "title": "疏散走道宽度检查",
                "description": "疏散走道净宽度不应小于1.4米",
                "condition": "element.Type == 'IfcSpace' AND element.IsCorridor == True",
                "threshold": 1.4,
                "unit": "m",
                "severity": "严重",
                "standard": "GB 50016-2014 建筑设计防火规范",
                "suggested_fix": "扩大走道宽度或调整空间布局"
            }
        ],
        "metadata": {
            "context_used": False,
            "optimization_level": "standard",
            "source": "AI规则引擎演示"
        }
    }